#if 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "flvio.h"
#include "scan.h"
#include "err.h"


struct tagkey {
	int time;
	unsigned track;
	int first;
	FILE *file;
	long pos;
	size_t len;
};

struct node {
	struct node *next;
	struct tagkey key;
};

static const long tmpfile_size = 1 << 30;
static struct node *head, *tail;
static unsigned node_num;

static scan_verdict
callback(scan_phase phase, struct tagbuf *b, struct context *ctx)
{
	struct node *n;
	FILE *tmp;

	if (phase != TAG)
		return OUTPUT;

	n = (struct node *)malloc(sizeof(*n));
	if (!n)
		die(1);
	n->key.time = ctx->tag[0].time;
	n->key.track = ctx->tag[0].track;
	n->key.first = 0;
	if (!ctx->out || (tail && tail->key.pos > tmpfile_size)) {
		ctx->out = tmpfile();
		n->key.first = 1;
		if (!ctx->out)
			die(1);
	}
	n->key.pos = ftell(ctx->out);
	if (n->key.pos < 0)
		die(1);
	n->key.file = ctx->out;
	n->key.len = b->hdrlen + b->len + 4;
	n->next = 0;
	if (!head)
		head = n;
	if (tail) {
		tail->next = n;
		tail = n;
	} else {
		tail = n;
	}
	node_num++;

	return OUTPUT;
}

static void help(void)
{
	printf("  Mux and reorder streams into one flv stream.\n"
	"Tags are sorted by timestamps.\n\n"
	"Usage: %s [FILE]...\n", progname);
}

static int cmp(const void *a, const void *b)
{
	const struct tagkey *x, *y;
	x = a;
	y = b;
	if (x->time != y->time)
		return x->time - y->time;
	if (x->track == y->track)
		return 0;
	if (x->track == FLV_TRACK_SCRIPT)
		return 1;
	if (y->track == FLV_TRACK_SCRIPT)
		return -1;
	if (x->track == FLV_TRACK_VIDEO)
		return 1;
	if (y->track == FLV_TRACK_VIDEO)
		return -1;
	if (x->track == FLV_TRACK_AUDIO)
		return 1;
	if (y->track == FLV_TRACK_AUDIO)
		return -1;
	return x->track - y->track;
}

static struct tagkey *sort()
{
	struct tagkey *tags;
	struct node *n;
	unsigned i;
	tags = (struct tagkey *)malloc(sizeof(*tags) * node_num);
	if (!tags)
		die(1);
	i = 0;
	for (n = head; n; n = head) {
		tags[i] = n->key;
		i++;
		head = n->next;
		free(n);
	}
	qsort(tags, node_num, sizeof(*tags), cmp);
	return tags;
}
static int output(const struct tagkey *tags, unsigned num, FILE *out)
{
	unsigned i;
	struct tagkey *k;
	fwrite("FLV\1\5\0\0\0\11\0\0\0\0", 13, 1, out);
	for (i = 0; i < num; i++) {
		k = &tags[i];
		if (k->first)
			rewind(k->file);
		
	}
}
int sort_main(int argc, char **argv)
{
	char **args, **name;
	FILE *in, *tmp;

	if (getopts(argc, argv, 0, 1) < 0) {
		help();
		return 2;
	}
	if (show_help) {
		help();
		return 0;
	}

	tmp = tmpfile();
	if (!tmp)
		die(1);

	args = getargs(argc, argv);
	for (name = args; *name; name++) {
		in = open_file(*name, 'r');
		if (!in)
			continue;

		scan(in, tmp, callback);

		close_file(in);
	}
	if (*args == 0) {
		in = open_file(0, 'r');
		scan(in, tmp, callback);
	}

	free(args);
	return 0;
}
#endif
